/*
 * @Description: 导出模板配置
 * @Author: Rfan
 * @Date: 2022-06-21 21:37:30
 * @LastEditTime: 2022-09-08 14:16:57
 */

import { useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { fetchLevelByATId } from '@/api/archivesType';
import { fetchMetadata } from '@/api/metadata';
import { delItemById } from '@/utils/list';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import ExcelPane from './components/ExcelPane';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { IBaseProp } from '../../../index';

interface ExportTemplateDialogProps extends ICommonDialog {
  data?: any; // 模板数据
  info: IBaseProp;
}

/**
 * @description: 模板配置弹窗
 * @param {ExportTemplateDialogProps} props 弹窗传入参数
 * @return {ReactDOM} 模板配置弹窗tsx
 */
const ExportTemplateDialog: FC<ExportTemplateDialogProps> = (props) => {
  const { visible, data, info, onClose } = props;
  // excel映射面板表单
  const [baseForm] = Form.useForm();
  // 模板数据
  const [template, setTemplate] = useState<any>({});
  // 层级列表（不含组件级）
  const [levelList, setLevelList] = useState([]);
  // 所有层级的元数据
  const [levelMetadata, setLevelMetadata] = useState<any>({});

  useEffect(() => {
    if (visible) {
      // 获取档案类型下所有层级
      fetchLevelByATId(info.archiveTypeId).then((res) => {
        const _list = delItemById(0, res.data, 'level');
        setLevelList(_list);
        _list.forEach((item: any) => {
          const { level } = item;
          const fieldQuery = {
            metadataFieldType: QUERY_METADATA_ALL,
            coordinate: {
              atType: info.atType,
              atCode: info.atCode,
              level
            }
          };
          !levelMetadata[level] &&
            fetchMetadata(fieldQuery).then((res: any) => {
              setLevelMetadata((state: any) => ({
                ...state,
                [level]: res.data
              }));
            });
        });
      });
    }
  }, [visible]);

  useEffect(() => {
    if (data) {
      setTemplate(data);
    }
  }, [data]);

  const onCancel = () => {
    onClose();
  };

  const saveTemplate = () => {
    saveExecl();
  };

  const saveExecl = () => {
    baseForm.submit();
  };

  return (
    <Modal
      title="导出字段模板设定"
      visible={visible}
      className="upload-template"
      width={650}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          onClick={() => {
            saveTemplate();
          }}
        >
          保存
        </Button>
      ]}
    >
      <ExcelPane
        levelList={levelList}
        levelMetadata={levelMetadata}
        form={baseForm}
        tplData={data}
        info={info}
        updateTemplate={setTemplate}
      />
    </Modal>
  );
};

export default ExportTemplateDialog;
